package base

import (
	"errors"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/xormplus/xorm"
	"path"
	"runtime"
	"share/dbs"
	"share/utils"
	"strings"
)

type JsonResult struct {
	Status  int
	Message string
	Data    interface{}
}

type BeegoController interface {
	GetString(string, ...string) string
	GetInt(string, ...int) (int, error)
}
type SuperController struct {
	beego.Controller
}

func (c *SuperController) CheckLogin() {
	var result JsonResult
	id := strings.Split(utils.DeBase64(c.Ctx.GetCookie("cf_token")), "|")[0]
	openid := c.Ctx.GetCookie("openid")
	if openid == "" || id == "" || openid != id {
		result.Message = "not login"
		result.Status = -1
		c.Data["json"] = result
		c.ServeJSON()
	}
}

/* 成功 */
func (c *SuperController) Success(data interface{}) {
	var result JsonResult
	result.Message = "success"
	result.Data = data
	c.Data["json"] = result
	c.ServeJSON()
}

//判断传入的error参数，如果不为空，则返回错误展示的JSON，并停止运行
func (c *SuperController) ErrStop(err interface{}) {
	switch err.(type) {
	case error:
		errStop(c, err.(error))
	case int:
		if err.(int) <= 0 {
			errStop(c, errors.New("error"))
		}
	case int64:
		if err.(int64) <= 0 {
			errStop(c, errors.New("error"))
		}
	}
}

func errStop(c *SuperController, err error) {
	var result JsonResult
	if err != nil {
		result.Status = -1
		result.Message = err.Error()
		_, file, line, _ := runtime.Caller(2)
		_, file = path.Split(file)
		beego.Error(fmt.Sprintf("[%s:%d]", file, line), err)
		c.Data["json"] = result
		c.ServeJSON()
		c.StopRun()
	}
}

func (c *SuperController) FYDB() *xorm.Engine {
	db, err := dbs.FYDB()
	errStop(c, err)
	return db
}
func (c *SuperController) AdminDB() *xorm.Engine {
	db, err := dbs.AdminDB()
	errStop(c, err)
	return db
}
